import { getSetting, chooseAddress, openSetting, showModal ,showToast} from "../../utils/asyncWx.js";
import regeneratorRuntime from '../../lib/runtime/runtime';
Page({
  data: {
    address: [],
    cart: [],
    list:[],
    allChecked: false,
    totalPrice: 0,
    totalNum: 0,
    ischoosed:true,
    isnotchoosed:false,
    back:true,
    itemid:0,
    openid:""
  }, 
  getopenid(){//修改
    let that=this
    wx.cloud.callFunction({
      name:"getopenid",
      success(res){
        console.log("获取openid成功",res.result.openid)
        that.setData({
          openid:res.result.openid
        })
      },
      fail(res){
        console.log("获取openid失败",res)
      }
    })
  },
  onLoad: function (options) {
    this.getopenid();
  },

  onShow() {
    // 获取的收货地址信息
    // 1 获取云数据库中的购物车数据
    let that=this 
    wx.cloud.database().collection("cart").where({
      _openid:this.data.openid
    })
    .get({
      success(res){
         console.log("请求购物车数据成功",res)
         that.setData({
           cart:res.data
         })
         console.log("123",cart)
      }, 
      fail(res){
         console.log("请求购物车数据失败",res)
      }
     })

     wx.cloud.callFunction({
       name:"getalllist",
       success(res){
         console.log("获取list数据成功",res)
         that.setData({
           list:res.result.data
         })
       },
       fail(res){
         console.log("获取list数据失败",res)
       }
     })
    
    //获取address里isselected为true的信息
    wx.cloud.database().collection("address").where({
      isselected:true,
      _openid:this.data.openid
    })
    .get({
      success(res){
        console.log("获取成功",res)
        that.setData({
          address:res.data
        })
       if(res.data.length==0)
       that.setData({
        ischoosed:false,
        isnotchoosed:true
      })
      else{
        that.setData({
          ischoosed:true,
          isnotchoosed:false
        })
      }
      }
    })
    
    let{cart}=this.data
    this.setCart(cart); 
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },


  

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 点击 收货地址
  async handleChooseAddress() {
    try {
      // 1 获取 权限状态
      const res1 = await getSetting();
      const scopeAddress = res1.authSetting["scope.address"];
      // 2 判断 权限状态
      if (scopeAddress === false) {
        await openSetting();
      }
      // 4 调用获取收货地址的 api
      let address = await chooseAddress();
      address.all = address.provinceName + address.cityName + address.countyName + address.detailInfo;

      // 5 存入到缓存中
      wx.setStorageSync("address", address);

    } catch (error) {
      console.log(error);
    }
  },
  // 商品的选中
  handeItemChange(e) {
    // 1 获取被修改的商品的id
    const goods_id = e.currentTarget.dataset.id;
    // 2 获取购物车数组 
    let { cart } = this.data;
    // 3 找到被修改的商品对象
    let index = cart.findIndex(v => v.goods_id === goods_id);
   
    // 4 选中状态取反
    cart[index].checked = !cart[index].checked;
    this.setCart(cart); 
    wx.cloud.database().collection("cart").where({
      goods_id:parseInt(cart[index].goods_id),_openid:this.data.openid}).update({
      data: {
        checked: cart[index].checked
      },
      success: function(res) {
        console.log(res.data)
      }
    })

  },
  // 设置购物车状态同时 重新计算 底部工具栏的数据 全选 总价格 购买的数量
  setCart(cart) {
    let allChecked = true;
    // 1 总价格 总数量
    let totalPrice = 0;
    let totalNum = 0;
    cart.forEach(v => {
      if (v.checked) {
        totalPrice += v.goods_num * v.goods_price;
        totalNum += v.goods_num;
      } else {
        allChecked = false;
      }
    })
    // 判断数组是否为空
    allChecked = cart.length != 0 ? allChecked : false;
    this.setData({
      cart,
      totalPrice, totalNum, allChecked
    });
    wx.setStorageSync("cart", cart);
  },
  // 商品全选功能
  handleItemAllCheck() {
    // 1 获取data中的数据
    let { cart, allChecked } = this.data;
    // 2 修改值
    allChecked = !allChecked;
    // 3 循环修改cart数组 中的商品选中状态 
    cart.forEach(v => v.checked = allChecked);
    // 4 把修改后的值 填充回data或者缓存中
    this.setCart(cart);
  },
  // 商品数量的编辑功能
  async handleItemNumEdit(e) {

    // 1 获取传递过来的参数 
    const { operation, id } = e.currentTarget.dataset;
    // 2 获取购物车数组
    let { cart} = this.data;
    // 3 找到需要修改的商品的索引
    const index = cart.findIndex(v => v.goods_id === id);
    // 4 判断是否要执行删除
    if (cart[index].goods_num === 1 && operation === -1) {
    let that=this;
    that.setData({
        modify_id:cart[index].goods_id
      })
    // 4.1 弹窗提示
    const res = await showModal({ content: "您是否要删除？" });
    if (res.confirm) {
      cart.splice(index, 1);
      this.setCart(cart);
      wx.cloud.database().collection("cart").where({
      goods_id:this.data.modify_id,
      _openid:this.data.openid
      }).remove({
            success: function(res) {
            console.log(res.data)
           }
        })
    }
    } else {
      // 5  进行修改数量
      cart[index].goods_num += operation;
      // 6 设置回缓存和data中
      this.setCart(cart);
     wx.cloud.database().collection("cart").where({//更新购物车中商品数量
        goods_id:id,
        _openid:this.data.openid
      }).update({
        data:{
          goods_num:cart[index].goods_num
        },
        success(res){
          console.log("购物车商品数量更新成功",res)
        },
        fail(res){
          console.log("购物车商品数量更新失败",res)
        }
      })
    }
  },
  // 点击 结算 
  async handlePay(option){
    // 1 判断收货地址
    const {address,totalNum,isnotchoosed}=this.data;
    if(isnotchoosed){
      await showToast({title:"您还没有选择收货地址"});
     return;
    }
    // 2 判断用户有没有选购商品
    if(totalNum===0){
      await showToast({title:"您还没有选购商品"});
      return ;
    }
    // 3 判断所选物品是否数量过多
    let {cart,list}=this.data;
    let {back,itemid}=this.data;
    cart.forEach(v=>{
      if(v.checked){
        itemid=v.goods_id;
        console.log(back)
        const index = list.findIndex(x => x.goods_id === itemid);
        console.log(list[index].sale_num)
        if(v.goods_num>list[index].sale_num){
          back=false; 
          wx.showToast({
            title: '商品数量不足', // 标题
            icon: 'none',  // 图标类型，默认success
            duration: 1500  // 提示窗停留时间，默认1500ms
          })
        }
        console.log(back)
      }
    })
    if(back){
      wx.navigateTo({
        url: '/pages/pay/pay?openid='+this.data.openid,
      success: function(res){
        res.eventChannel.emit('acceptDatafromCart',{cart:option.currentTarget.cart})
      }
    });

    }
      
  },







  lianjie(){    //修改！！！
    wx.navigateTo({
      url: '../selectaddress/selectaddress?openid='+this.data.openid
    })
  }
})

